package com.sendpo.zjx.sendpo.activity;


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.UserDomain;

import com.sendpo.zjx.sendpo.fragment.privatedingdan.AllFragment;
import com.sendpo.zjx.sendpo.fragment.privatedingdan.BaseDingdanFragment;
import com.sendpo.zjx.sendpo.fragment.privatedingdan.DaifahuoFragment;
import com.sendpo.zjx.sendpo.fragment.privatedingdan.DaifukuanFragment;
import com.sendpo.zjx.sendpo.fragment.privatedingdan.DaishouhuoFragment;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.MD5Util;
import com.sendpo.zjx.sendpo.utils.PayDomain;
import com.sendpo.zjx.sendpo.utils.PayResult;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;
import com.shizhefei.view.viewpager.SViewPager;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by zjx on 2018
 */

public class PrivateAllDindanListActivity extends AppCompatActivity {
    public Dialog confirm_dialog = null;
    public static final int REQUEST_EVALUATE = 10333;
    public static String[] titles = {"全部","待付款", "待发货", "待收货"};
    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.indicator)
    ScrollIndicatorView indicator;
    @BindView(R.id.viewpager)
    SViewPager viewpager;
    private AllFragment allfragment;
    private DaifukuanFragment daifukuan;
    private DaifahuoFragment daifahuo;
    private DaishouhuoFragment daishouhuo;


    public int jifentype = 0;
    private String kouchujifen = "";
    public Dialog loadingdialog = null;
    private String orderId = "";

    private Dialog paydialog;
    private RadioGroup radioGroup;
    private TextView readby;

    private IndicatorViewPager indicatorViewPager;

    Button paybt;
    EditText confirm_edit_tv;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HttpUrl.SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Gson gson=new Gson();
                        PayDomain pay=gson.fromJson(payResult.getResult(),PayDomain.class);
                        //     paysuccess(orderId);
                        //paysuccess(AllDindanListActivity.this.orderId);
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        System.out.println("***************"+payResult.getResult());
                        Toast.makeText(getApplicationContext(), "支付成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(getApplicationContext(), "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        };
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alldindan);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();
         initPayDialog();
        webUserSserver();
    }

    private void initComponent() {
        viewpager.setCanScroll(false);
        viewpager.setOffscreenPageLimit(1);
        indicatorViewPager = new IndicatorViewPager(this.indicator, this.viewpager);
        List<BaseDingdanFragment> fragments=new ArrayList<>();
        fragments.add(allfragment=new AllFragment());
        fragments.add(daifukuan=new DaifukuanFragment());
        fragments.add(daifahuo=new DaifahuoFragment());
        fragments.add(daishouhuo=new DaishouhuoFragment());


        indicatorViewPager.setAdapter(new FragmentIndicatorAdapter(getSupportFragmentManager(), fragments));
        indicatorViewPager.setClickIndicatorAnim(true);
        indicatorViewPager.setIndicatorOnTransitionListener(new OnTransitionTextListener().setColor(getResources().getColor(R.color.default_theme), getResources().getColor(R.color.default_gray)));
        ColorBar colorBar = new ColorBar(this, getResources().getColor(R.color.default_theme), 5);
        colorBar.setWidth(120);
        indicatorViewPager.setIndicatorScrollBar(colorBar);

        indicatorViewPager.setOnIndicatorPageChangeListener(new IndicatorViewPager.OnIndicatorPageChangeListener() {
            @Override
            public void onIndicatorPageChange(int preItem, int currentItem) {

            }
        });
        this.indicatorViewPager.setCurrentItem(getIntent().getIntExtra("position", 0), false);
}

    public void webUserSserver() {
        final List localList = Xutils.queryAll(getApplication(), User.class);
        if ((localList == null) || (localList.size() == 0)) {
            return;
        }
        final User localUser = (User) localList.get(0);
        Map<String, String> map = new HashMap<>();
        map.put("userId", localUser.getUserId() + "");
        Xutils.POST(HttpUrl.queryuserbyid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("**********************rwebUserSserveresult:" + result);
                Gson gson = new Gson();
                UserDomain domain = gson.fromJson(result, UserDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        User data = domain.getData();
                        data.setId(localUser.getId());
                        Xutils.update(getApplication(), data);

                        System.out.println("*********************************data:" + data.toString());
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void paysuccess(String orderId) {
        HashMap map = new HashMap();
        map.put("orderId", orderId + "");
        Xutils.POST(HttpUrl.ordermerchandiseupdatebydisanfang, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
              webUserSserver();
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    Toast.makeText(PrivateAllDindanListActivity.this.getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                    switch (jsonObject.getInt("message")){
                        case HttpCode.SUCCESS:
                            paydialog.dismiss();
                            finish();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }

  private  class FragmentIndicatorAdapter extends    IndicatorViewPager.IndicatorFragmentPagerAdapter{
      private List<BaseDingdanFragment> fragments;
      public FragmentIndicatorAdapter(FragmentManager fragmentManager,List<BaseDingdanFragment> fragments) {
          super(fragmentManager);
          this.fragments=fragments;
      }

      @Override
      public int getCount() {
          return this.fragments.size();
      }

      @Override
      public View getViewForTab(int position, View convertView, ViewGroup container) {
          if (convertView == null) {
              convertView = View.inflate(PrivateAllDindanListActivity.this, R.layout.tab_focus, null);
          }
          TextView textView = (TextView) convertView;
          textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
          textView.setText(titles[position]);
          return textView;
      }

      @Override
      public Fragment getFragmentForPage(int position) {
          return (Fragment)this.fragments.get(position);
      }

  }
    public void initPayDialog() {
        loadingdialog = new Dialog(this);
        loadingdialog.setContentView(R.layout.dialog_loading);
        loadingdialog.setCanceledOnTouchOutside(false);
        loadingdialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        confirm_dialog=new Dialog(this);
        confirm_dialog.setContentView(R.layout.dialog_paymoney);
        confirm_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        readby = confirm_dialog.findViewById(R.id.readby);
        confirm_edit_tv=confirm_dialog.findViewById(R.id.edit_tv);
        TextView exitbt=confirm_dialog.findViewById(R.id.exitbt);
        exitbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                confirm_dialog.dismiss();
            }
        });
        TextView readby=confirm_dialog.findViewById(R.id.readby);
        exitbt.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View paramAnonymousView)
            {
                PrivateAllDindanListActivity.this.confirm_dialog.dismiss();
            }
        });
        paydialog=new Dialog(this);
        paydialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        paydialog.setContentView(R.layout.dialog_rechargemoney);
        radioGroup=paydialog.findViewById(R.id.rg_pay);
        TextView recharage_title=paydialog.findViewById(R.id.recharage_title);
        recharage_title.setText("结算支付");
        EditText recharge_edit= paydialog.findViewById(R.id.recharge_edit);
        recharge_edit.setVisibility(View.GONE);
        View yuyue_left=paydialog.findViewById(R.id.yuyue_left);
        yuyue_left.setVisibility(View.VISIBLE);

        final RadioButton pay_moneypackage=paydialog.findViewById(R.id.pay_moneypackage);
        pay_moneypackage.setVisibility(View.VISIBLE);
        pay_moneypackage.setChecked(true);
        final RadioButton pay_wexin=paydialog.findViewById(R.id.pay_wexin);
        pay_wexin.setChecked(false);
        paydialog.findViewById(R.id.moneycount_rl);
         paybt=paydialog.findViewById(R.id.paybt);
        yuyue_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_moneypackage.setChecked(true);
            }
        });
        RelativeLayout wx_rl=paydialog.findViewById(R.id.wx_rl);
        wx_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_wexin.setChecked(true);
            }
        });
        final RadioButton pay_paypackage=paydialog.findViewById(R.id.pay_paypackage);
        RelativeLayout pay_rl=paydialog.findViewById(R.id.pay_rl);
        pay_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_paypackage.setChecked(true);
            }
        });
    }






    public void showPay(final String orderId) {
        this.paydialog.show();
        this.orderId = orderId;
        this.kouchujifen = kouchujifen;
        this.jifentype = jifentype;
        paybt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<User> userList= Xutils.queryAll(getApplication(),User.class);
                if(userList==null){
                    return;
                }
                User user=userList.get(0);
                switch (radioGroup.getCheckedRadioButtonId()){
                    case R.id.pay_moneypackage:
                        if(TextUtils.isEmpty(user.getUserPaypassword())){
                            Intent paypass=new Intent(PrivateAllDindanListActivity.this,ModifyPayPassActivity.class);
                            startActivity(paypass);
                            return;
                        }
                        paydialog.dismiss();
                        confirm_edit_tv.getText().clear();
                        confirm_dialog.show();
                        break;
                    case R.id.pay_wexin:
                        Toast.makeText(getApplicationContext(),"微信支付"
                                ,Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.pay_paypackage:
                        confirm_dialog.dismiss();
                        zhifubao(orderId,user.getUserId()+"");
                        break;
                }
            }
        });

        readby.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(TextUtils.isEmpty(confirm_edit_tv.getText().toString().trim())){
                    Toast.makeText(getApplicationContext(),"支付密码不能为空",Toast.LENGTH_LONG).show();
                    return;
                }
                List<User> userList= Xutils.queryAll(getApplication(),User.class);
                if(userList==null){
                    return;
                }
                User user=userList.get(0);
                if(TextUtils.equals(MD5Util.getMD5(confirm_edit_tv.getText().toString().trim()), user.getUserPaypassword())){
                    yuyue(orderId,user.getUserId()+"");
                    confirm_dialog.dismiss();
                    //   reduceMoney(paymoney+"",orderId);
                }else{
                    Toast.makeText(getApplicationContext(),"输入支付密码不正确",Toast.LENGTH_LONG).show();
                }

            }
        });

    }

    @OnClick(value = {R.id.backbt})
    public void onMyClick(View view){
        switch (view.getId()){
            case R.id.backbt:
                finish();
                break;
        }
    }


    //余额支付
    public void  yuyue(String orderId,String userId){
        Map<String,String>  map=new HashMap<>();
        map.put("id",""+orderId);
        map.put("userId",""+userId);
        Xutils.GET(HttpUrl.customizeorderUserMoneyPay, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject json=new JSONObject(result);

                    if(json.getBoolean("flag")){
                        Toast.makeText(getApplicationContext(),"余额支付成功",Toast.LENGTH_SHORT).show();
                        finish();
                    }else{
                        Toast.makeText(getApplicationContext(),"余额支付失败",Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void  zhifubao(String orderId,String userId){
        Map<String,String>  map=new HashMap<>();
        map.put("id",""+orderId);
        map.put("userId",""+userId);
        Xutils.GET(HttpUrl.customizeorderAliPay, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    final JSONObject json=new JSONObject(result);
                    if(json.getBoolean("flag")){
                        Toast.makeText(getApplicationContext(),"打开支付宝",Toast.LENGTH_SHORT).show();
                        Runnable payRunnable = new Runnable() {
                            @Override
                            public void run() {
                                PayTask alipay = new PayTask(PrivateAllDindanListActivity.this);
                                Map<String, String> result = null;
                                try {
                                    result = alipay.payV2(json.getString("data"), true);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                Message msg = new Message();
                                msg.what = HttpUrl.SDK_PAY_FLAG;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
                            }
                        };
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                    }else{
                        Toast.makeText(getApplicationContext(),json.getString("msg"),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getApplicationContext(),"请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
